package com.cxz.kotlin.baselibs.ext

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import com.jakewharton.rxbinding2.view.RxView
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

/**
 * 点击事件
 */
fun View.rxClick(delay: Long, click: () -> Unit, disposableBind: ((Disposable) -> Unit)?) {
    RxView.clicks(this)
        .throttleFirst(delay, TimeUnit.SECONDS)
        .subscribe {
            click()
        }.let {
            if (disposableBind != null) disposableBind(it)
        }
}

/**
 * 点击事件
 */
fun View.rxClickSimple(click: () -> Unit) {
    RxView.clicks(this)
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribe {
            click()
        }
}

/**
 * 显示View
 */
fun View.visiable() {
    visibility = View.VISIBLE
}

/**
 * 隐藏View
 */
fun View.gone() {
    visibility = View.GONE
}


//-----扩展属性-----

var View.bottomMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).bottomMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).bottomMargin = value
    }


var View.topMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).topMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).topMargin = value
    }


var View.rightMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).rightMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).rightMargin = value
    }

var View.leftMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).leftMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).leftMargin = value
    }

/**
 * View 转 bitmap
 */
fun View.view2Bitmap(): Bitmap {
    var ret = Bitmap.createBitmap(this.width, this.height, Bitmap.Config.ARGB_8888)
    var canvas = Canvas(ret)
    var bgDrawable = this.background
    bgDrawable?.draw(canvas) ?: canvas.drawColor(Color.WHITE)
    this.draw(canvas)
    return ret
}